import 'dart:async';

import 'package:flutter/foundation.dart';
import 'package:flutter/services.dart';

import '../bean/bean.dart';
import '../enums/enums.dart';
import '../platform_interface/audio_output_device_new_platform_interface.dart';

/// An implementation of [AudioOutputDeviceNewPlatform] that uses method channels.
class MethodChannelAudioOutputDeviceNew extends AudioOutputDeviceNewPlatform {
  /// The method channel used to interact with the native platform.
  @visibleForTesting
  final methodChannel = const MethodChannel('audio_output_device_new');

  @visibleForTesting
  final eventChannel = const EventChannel('audio_output_device_new/event');

  StreamSubscription? _eventSubs;
  MethodChannelAudioOutputDeviceNew(){
    _classicDeviceDisconnectedController = StreamController<bool>.broadcast();
    _classicDeviceDisconnected = _classicDeviceDisconnectedController.stream;

    _eventSubs = eventChannel.receiveBroadcastStream()
        .map((dynamic e) => EventBean.fromMap(e.cast<String, dynamic>())).listen(_onEvent);
  }

  late final StreamController<bool> _classicDeviceDisconnectedController;
  late final Stream<bool> _classicDeviceDisconnected;

  @override
  Stream<bool> get classicDeviceDisconnected => _classicDeviceDisconnected;

  void _onEvent(EventBean event){
    switch(event.name){
      case Event.onClassicDeviceDisconnected:
        _classicDeviceDisconnectedController.add(true);
        break;
      default:
        break;
    }
  }

  @override
  Future<String?> getPlatformVersion() async {
    final version = await methodChannel.invokeMethod<String>('getPlatformVersion');
    return version;
  }

  @override
  Future<List<BleDevice>> getA2dpConnectedDevices() async{
    List<BleDevice> devices = [];
    List list = (await methodChannel.invokeMethod<List>('getA2dpConnectedDevices')??[]);
    for (var it in list) {
      devices.add(BleDevice.fromMap(it.cast<String, dynamic>()));
    }
    return devices;
  }
}
